﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Things.OrderPlan.Models;

namespace Things.OrderPlan
{
    public class OrderPlanRepository
    {
        public bool Restore(OrderPlan.Models.OrderPlan order)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                if (container.OrderPlanSet.Where(p => p.Id == order.Id).Count() > 0)
                {
                    container.OrderPlanSet.Attach(order);
                    container.ObjectStateManager.ChangeObjectState(order, System.Data.EntityState.Modified);
                }
                else
                {
                    container.OrderPlanSet.AddObject(order);
                }

                if (container.SaveChanges() > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public bool Delete(OrderPlan.Models.OrderPlan order)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                container.OrderPlanSet.DeleteObject(order);
                if (container.SaveChanges() > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public OrderPlan.Models.OrderPlan Find(Guid orderId)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.OrderPlanSet.Where(p => p.Id == orderId).FirstOrDefault<OrderPlan.Models.OrderPlan>();
            }
        }

        public OrderPlan.Models.OrderPlan Find(int orderPlanNumber)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.OrderPlanSet.Where(p => p.OrderPlanNumber == orderPlanNumber).FirstOrDefault<OrderPlan.Models.OrderPlan>();
            }
        }

        public List<OrderPlan.Models.OrderPlan> FindAll(Guid goodsId)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.OrderPlanSet.Where(p => p.GoodsId == goodsId).ToList<OrderPlan.Models.OrderPlan>();
            }
        }

        public List<OrderPlan.Models.OrderPlan> FindAll(string userAccount)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.OrderPlanSet.Where(p => p.UserName == userAccount).ToList<OrderPlan.Models.OrderPlan>();
            }
        }
    }
}
